package hk.com.fgoproduction.getdroplets.Lib.Common

import android.app.Application
import android.content.Context
import android.content.IntentFilter
import android.util.Log
import hk.com.fgoproduction.getdroplets.BroadcastAndNoti.NotiReceiver
import hk.com.fgoproduction.getdroplets.DropboxAPI.AFile
import java.util.*
import java.util.concurrent.*

class ThisApplication : Application () {

    val threadPool: ThreadPoolExecutor = ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), 5L * 60L * 1000L, TimeUnit.MILLISECONDS, LinkedBlockingQueue<Runnable>())
    var cb: BgThreadCallback? = null
    var filePathQueue = ConcurrentLinkedQueue<String>()

    val jobSchedulerList = ArrayList<Int>()
    val token = ArrayList<Any>()
    var tasks = 0
    val tasksLimit = 1

    override fun onCreate() {
        super.onCreate()

        threadPool.allowCoreThreadTimeOut(true)
        threadPool.prestartAllCoreThreads()
//        for (i in 0..tasksLimit) {
//            token.add(Any())
//        }
    }

    override fun onTerminate() {
        super.onTerminate()

        threadPool.shutdownNow()
    }

    /**
     * Singleton file API wrapper factory
     * @param _client Dropbox client
     * @return file API wrapper instance
     */
    fun fileApiFactory(ctx: Context): AFile {
        if (instance == null)
            synchronized(AFile::class.java) {
                if (instance == null)
                    instance = AFile(ctx)
            }

        return instance as AFile
    }

    fun clearFileApiInstance() {
        instance = null
    }

    private var instance: AFile? = null

    /**
     * Thread pool task receiver
     * @param runnable task
     */
    fun runOnBg(runnable: Runnable) {
        threadPool.submit(runnable)
    }

    /**
     * Thread pool task receiver with main thread blocking
     * @param runnable task
     */
    fun runOnBgAndJoin(runnable: Runnable) {
        threadPool.submit(runnable).get()
    }

    fun runOnBgWithCb(runnable: Runnable, cb: BgThreadCallback) {
        val thread = Thread(runnable)
        threadPool.submit {
            thread.run()
            thread.join()
            cb.threadFinish()
        }
    }

    interface BgThreadCallback {
        fun threadFinish()
    }

}

